package com.zhuoyue.biz.core.api.service.impl.device;

import com.zhuoyue.biz.core.api.domain.DeviceAndGatewayDO;
import com.zhuoyue.biz.core.api.domain.TblPasswordShare;
import com.zhuoyue.biz.core.api.dto.req.ControlReq;
import com.zhuoyue.biz.core.command.cmd.common.fbf.FingerprintLock0Fbf0202;
import com.zhuoyue.biz.core.command.service.CmdSendService;
import com.zhuoyue.biz.core.command.service.CmdSqlHandleService;
import com.zhuoyue.common.constant.RedisKey;
import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.AesUtils;
import com.zhuoyue.common.utils.Time;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wjming
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FingerprintLockCommon {

    private final CmdSendService cmdSendService;

    private final RedisTemplate redisTemplate;

    private final CmdSqlHandleService cmdSqlHandleService;

    private static final String ZERO_ZERO = "00";
    private static final String CMD = "cmd";
    private static final String PSD = "psd";
    private static final String TYPE = "type";
    private static final String MANY_TIMES = "many_times";
    private static final String CANCEL = "cancel";

    public String fingerDeal(DeviceAndGatewayDO deviceAndGatewayDO, ControlReq controlReq) {
        String cmd = "";
        List<String> list = cmdSendService.sendPsdSecretKeyToLock(deviceAndGatewayDO.getZigbeeMac(), deviceAndGatewayDO.getGatewayMac());
        try {
            Object isOk;
            int count = 0;
            do {
                Thread.sleep(1000);
                isOk = redisTemplate.opsForValue().get(RedisKey.fingerprintLockPsd(deviceAndGatewayDO.getZigbeeMac()));
                if (isOk != null && isOk != "") {
                    break;
                }
                count++;
            } while (count < 10);

            if (isOk != null && StringUtils.equals(ZERO_ZERO, (String) isOk)) {
                Map<String, String> cmdAndPsd = FingerprintLock0Fbf0202.control(deviceAndGatewayDO, controlReq, list);
                cmd = cmdAndPsd.get(CMD);
                if (cmdAndPsd.get(PSD) != null && cmdAndPsd.get(TYPE) != null) {
                    TblPasswordShare passwordShare = new TblPasswordShare();
                    passwordShare.setLockPassword(AesUtils.encrypt(cmdAndPsd.get(PSD)));
                    passwordShare.setState("0");
                    passwordShare.setDeviceMac(deviceAndGatewayDO.getZigbeeMac());
                    passwordShare.setType(cmdAndPsd.get(TYPE));
                    //先删除之前的设备mac对应的type的类型
                    cmdSqlHandleService.deletePassword(passwordShare);
                    if (StringUtils.equals(MANY_TIMES, cmdAndPsd.get(TYPE))) {
                        passwordShare.setBeginTime(Time.getDateTimeOfTimestamp(Long.parseLong(controlReq.getActions().get("startTime").toString())));
                        passwordShare.setEndTime(Time.getDateTimeOfTimestamp(Long.parseLong(controlReq.getActions().get("endTime").toString())));
                        Long endTime = Long.parseLong(controlReq.getActions().get("endTime").toString());
                        endTime = endTime / 1000 - Time.toGetNowLongSecond();
                        redisTemplate.opsForValue().set(RedisKey.fingerprintLockTimePsd(deviceAndGatewayDO.getZigbeeMac()),
                                cmdAndPsd.get(PSD), endTime, TimeUnit.SECONDS);
                    }
                    cmdSqlHandleService.setPassword(passwordShare);
                } else {
                    if (StringUtils.isNotEmpty(cmdAndPsd.get(CANCEL)) && StringUtils.isNotEmpty(cmdAndPsd.get(TYPE))) {
                        TblPasswordShare passwordShare = new TblPasswordShare();
                        passwordShare.setState("1");
                        passwordShare.setType(cmdAndPsd.get(TYPE));
                        passwordShare.setDeviceMac(deviceAndGatewayDO.getZigbeeMac());
                        cmdSqlHandleService.updatePassWord(passwordShare);
                        redisTemplate.delete(RedisKey.fingerprintLockTimePsd(deviceAndGatewayDO.getZigbeeMac()));
                    }
                }
            } else {
                throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND.getCode(), "密钥发送失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return cmd;
    }
}
